package slxy.jiangtao.dts.service.sys;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.entity.sys.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by JiangTao on 2017/1/12.
 */
@Service("userService")
public class UserService {
    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private CommonService commonService;
    @Autowired
    private MenuSevice menuSevice;

    /**
     * 根据主键获取用户
     */
    public User getById(Serializable id) {
        User user = commonService.get(User.class, id);
        return user;
    }

    /**
     * 添加用户
     */
    public int insert(User user) {
        user.setUserType(commonService.get(Role.class, user.getRoleId()).getType());
        return (int) commonService.save(user);
    }

    /**
     * 根据主键id删除一个用户
     */
    public void delete(Serializable id) {
        commonService.deleteEntityById(User.class, id);
    }

    /**
     * 更新用户信息
     */
    public void update(User user) {
        user.setUserType(commonService.get(Role.class, user.getRoleId()).getType());
        commonService.updateEntity(user);
    }

    /**
     * 获取所有用户
     */
    public List<User> getAll() {
        return commonService.getList(User.class);
    }

    /**
     * 获取所有在职人员
     */
    public List<User> getAllJob() {
        return commonService.findByProperty(User.class, "statu", Constants.STATU_FLAG_NORMAL);
    }


    /**
     * 获取所有在职干部
     */
    public List<User> getManagers() {
        //根据用户类型获取负责人列表
        DetachedCriteria dc2 = DetachedCriteria.forClass(User.class);
        dc2.add(Restrictions.in("userType", Constants.MANAGER_IDS));
        List<User> userList = commonService.findByDetached(dc2);
        return userList;
    }

    /**
     * 获取相关部门的干部
     *
     * @param departId 部门id
     */
    public List<User> getManagerByDepartMent(Integer departId) {
        List<User> managerAll = getManagers();
        List<User> departManager = new ArrayList<>();
        Optional.ofNullable(managerAll).ifPresent(
                users ->
                        users.forEach(
                                user -> {
                                    if (user.getDepartId().equals(departId)) {
                                        departManager.add(user);
                                    }
                                }
                        )
        );
        return departManager;
    }

    /**
     * 获取所有非社长的干部
     *
     * @param presidentId 主席团部门id
     */
    public List<User> getManagerExcludPresident(Integer presidentId) {
        List<User> managerAll = getManagers();
        List<User> departManager = new ArrayList<>();
        Optional.ofNullable(managerAll).ifPresent(
                users ->
                        users.forEach(
                                user -> {
                                    if (user.getDepartId() != presidentId) {
                                        departManager.add(user);
                                    }
                                }
                        )
        );
        return departManager;
    }

    /**
     * 根据id集合获取用户集
     */
    public List<User> getUsersByIds(Integer[] ids) {
        DetachedCriteria dc2 = DetachedCriteria.forClass(User.class);
        dc2.add(Restrictions.in("id", ids));
        List<User> userList = commonService.findByDetached(dc2);
        return userList;
    }


    /**
     * 登录验证
     */
    public boolean loginCheck(HttpServletRequest request, String no, String password) {
        User user = commonService.findUniqueByProperty(User.class, "no", no);
        if (user != null && user.getPassword().equals(password)) {
            request.getSession().setAttribute(Constants.USER_IN_SESSION, user);
            if (user.getRoleId() != null) {
                List<Integer> menuIds = commonService.findListbySql("select menu_id from role_menu where role_id = " + user.getRoleId());
                String rolemenuids = menuIds.toString().replace("[","[,").replace("]",",]").replace(" ","");
                System.out.println(rolemenuids);
                request.getSession().setAttribute(Constants.MENUS_IN_SESSION,rolemenuids);
            }
            return true;
        }
        return false;
    }

    /**
     * 构造在职人员与部门的二叉树
     */
    public List<ZtreeVo> userDepartZtree() {
        List<User> users = getAllJob();
        List<Depart> departs = commonService.getList(Depart.class);
        List<ZtreeVo> ztreeVoList = new ArrayList<>();
        Optional.ofNullable(departs).ifPresent(
                departList ->
                        departList.forEach(
                                depart -> {
                                    //对部门的id全部减去1000，作为与用户id的区别，
                                    ZtreeVo ztreeVo = new ZtreeVo();
                                    ztreeVo.setId(depart.getId() - 1000);
                                    ztreeVo.setPid(0);
                                    ztreeVo.setName(depart.getName());
                                    ztreeVoList.add(ztreeVo);
                                }
                        )
        );
        Optional.ofNullable(users).ifPresent(
                userList ->
                        userList.forEach(
                                user -> {
                                    if (user.getDepartId() != null) {
                                        ZtreeVo ztreeVo = new ZtreeVo();
                                        ztreeVo.setId(user.getId());
                                        ztreeVo.setName(user.getName());
                                        ztreeVo.setPid(user.getDepartId() - 1000);//对部门的id全部减去1000，作为与用户id的区别
                                        ztreeVoList.add(ztreeVo);
                                    }
                                }
                        )
        );
        return ztreeVoList;
    }
}
